/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.kungkhies.desktop.activity.explorer;

import com.kungkhies.desktop.library.entities.Activity;
import java.util.List;
import java.util.logging.Logger;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;
import javax.swing.ActionMap;
import javax.swing.SwingUtilities;
import org.openide.util.NbBundle;
import org.openide.windows.TopComponent;
import org.netbeans.api.settings.ConvertAsProperties;
import org.openide.awt.ActionID;
import org.openide.awt.ActionReference;
import org.openide.explorer.ExplorerManager;
import org.openide.explorer.ExplorerUtils;
import org.openide.nodes.Children;
import org.openide.util.RequestProcessor;
import org.openide.windows.WindowManager;

/**
 * Top component which displays something.
 */
@ConvertAsProperties(dtd = "-//com.kungkhies.desktop.activity.explorer//ActivityExplorer//EN",
autostore = false)
@TopComponent.Description(preferredID = "ActivityExplorerTopComponent",
//iconBase="SET/PATH/TO/ICON/HERE", 
persistenceType = TopComponent.PERSISTENCE_ALWAYS)
@TopComponent.Registration(mode = "explorer", openAtStartup = false)
@ActionID(category = "Window", id = "com.kungkhies.desktop.activity.explorer.ActivityExplorerTopComponent")
@ActionReference(path = "Menu/Window" /*, position = 333 */)
@TopComponent.OpenActionRegistration(displayName = "#CTL_ActivityExplorerAction",
preferredID = "ActivityExplorerTopComponent")
public final class ActivityExplorerTopComponent extends TopComponent implements ExplorerManager.Provider
{
    private static ExplorerManager em = new ExplorerManager();
    private static final String PREFERRED_ID = "ActivityExplorerTopComponent";
    private static ActivityExplorerTopComponent instance;
    
    public ActivityExplorerTopComponent()
    {
        initComponents();
        setName(NbBundle.getMessage(ActivityExplorerTopComponent.class, "CTL_ActivityExplorerTopComponent"));
        setToolTipText(NbBundle.getMessage(ActivityExplorerTopComponent.class, "HINT_ActivityExplorerTopComponent"));
        
        ActionMap map = this.getActionMap();
        map.put("delete", ExplorerUtils.actionDelete(em, true)); //NOI18N
        associateLookup(ExplorerUtils.createLookup(em, map));
        RequestProcessor.getDefault().post(new Runnable () {
            @Override
            public void run() {
                readActivity();
            }
        });
        
        refreshNode();
        
        //associateLookup(ExplorerUtils.createLookup(em, getActionMap()));

    }
    
    /**
     * Gets default instance. Do not use directly: reserved for *.settings files only,
     * i.e. deserialization routines; otherwise you could get a non-deserialized instance.
     * To obtain the singleton instance, use {@link #findInstance}.
     */
    public static synchronized ActivityExplorerTopComponent getDefault() {
        if (instance == null) {
            instance = new ActivityExplorerTopComponent();
        }
        return instance;
    }

    /**
     * Obtain the CustomerTopComponent instance. Never call {@link #getDefault} directly!
     */
    public static synchronized ActivityExplorerTopComponent findInstance() {
        TopComponent win = WindowManager.getDefault().findTopComponent(PREFERRED_ID);
        if (win == null) {
            Logger.getLogger(ActivityExplorerTopComponent.class.getName()).warning(
                    "Cannot find " + PREFERRED_ID + " component. It will not be located properly in the window system.");
            return getDefault();
        }
        if (win instanceof ActivityExplorerTopComponent) {
            return (ActivityExplorerTopComponent) win;
        }
        Logger.getLogger(ActivityExplorerTopComponent.class.getName()).warning(
                "There seem to be multiple components with the '" + PREFERRED_ID
                + "' ID. That is a potential source of errors and unexpected behavior.");
        return getDefault();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        beanTreeView1 = new org.openide.explorer.view.BeanTreeView();

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(beanTreeView1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 417, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(beanTreeView1, javax.swing.GroupLayout.DEFAULT_SIZE, 418, Short.MAX_VALUE)
        );
    }// </editor-fold>//GEN-END:initComponents

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private org.openide.explorer.view.BeanTreeView beanTreeView1;
    // End of variables declaration//GEN-END:variables
    @Override
    public void componentOpened()
    {
        // TODO add custom code on component opening
    }

    @Override
    public void componentClosed()
    {
        // TODO add custom code on component closing
    }

    void writeProperties(java.util.Properties p)
    {
        // better to version settings since initial version as advocated at
        // http://wiki.apidesign.org/wiki/PropertyFiles
        p.setProperty("version", "1.0");
        // TODO store your settings
    }

    void readProperties(java.util.Properties p)
    {
        String version = p.getProperty("version");
        // TODO read your settings according to their version
    }
    
     public static void refreshNode()
    {
        EntityManager entityManager = Persistence.createEntityManagerFactory("KungkhieEntityLibraryPU").createEntityManager();
        Query query = entityManager.createQuery("SELECT i FROM Activity i");
        List<Activity> resultList =  query.getResultList();
        em.setRootContext(new ActivityRootNode(Children.create(new ActivityChildFactory(resultList), true)));
    }

    @Override
    public ExplorerManager getExplorerManager()
    {
        return em;
    }
    
    private void readActivity() {
        //JavaDBSupport.ensureStartedDB();
        EntityManagerFactory factory = Persistence.createEntityManagerFactory("KungkhieEntityLibraryPU");
        if (factory == null) {
            // XXX: message box?
            return ;
        }
        EntityManager entityManager = null;
        try {
            entityManager = factory.createEntityManager();
        } catch (RuntimeException re) {
            // XXX: message box?
            return ;
        }
        final Query query = entityManager.createQuery("SELECT c FROM Activity c");
        SwingUtilities.invokeLater(new Runnable () {
            @Override
            public void run() {
                @SuppressWarnings("unchecked")
                List<Activity> resultList = query.getResultList();
                em.setRootContext(new ActivityRootNode(Children.create(new ActivityChildFactory(resultList), true)));
            }
        });
    }
}
